﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Security.Claims;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// 模拟用户登录中间件扩展类
    /// </summary>
    internal static class BootstrapAdminSimulateUserExtensions
    {
        /// <summary>
        /// 模拟指定用户 仅 DEBUG 环境下生效
        /// </summary>
        /// <param name="builder">IApplicationBuilder 实例</param>
        /// <remarks>使用配置文件项 SimulateUserName 值</remarks>
        internal static IApplicationBuilder UseBootstrapAdminSimulate(this IApplicationBuilder builder)
        {
            builder.Use(async (context, next) =>
            {
                var userName = builder.ApplicationServices.GetRequiredService<IConfiguration>().GetValue("SimulateUserName", "");
                if (!string.IsNullOrEmpty(userName))
                {
                    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                    context.User = new ClaimsPrincipal(identity);
                }
                await next();
            });
            return builder;
        }
    }
}
